package com.service;

import com.entity.WeiJianDispatchRecord;
import com.repository.WeiJianDispatchRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class WeiJianDispatchRecordService {

    @Autowired
    private WeiJianDispatchRecordRepository weiJianDispatchRecordRepository;

    /**
     * 保存派工记录
     * @param weiJianDispatchRecord 派工记录
     * @return 保存后的对象
     */
    public WeiJianDispatchRecord save(WeiJianDispatchRecord weiJianDispatchRecord) {
        if (weiJianDispatchRecord.getId() == null) {
            weiJianDispatchRecord.setCreateTime(new Date());
        }
        weiJianDispatchRecord.setUpdateTime(new Date());
        return weiJianDispatchRecordRepository.save(weiJianDispatchRecord);
    }

    /**
     * 根据ID删除派工记录
     * @param id ID
     */
    public void deleteById(Integer id) {
        weiJianDispatchRecordRepository.deleteById(id);
    }

    /**
     * 根据ID获取派工记录
     * @param id ID
     * @return 派工记录
     */
    @Transactional(readOnly = true)
    public Optional<WeiJianDispatchRecord> findById(Integer id) {
        return weiJianDispatchRecordRepository.findById(id);
    }

    /**
     * 分页查询派工记录
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<WeiJianDispatchRecord> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return weiJianDispatchRecordRepository.findAll(pageable);
    }

    /**
     * 根据项目名称模糊查询派工记录
     * @param projectName 项目名称
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<WeiJianDispatchRecord> findByProjectNameContaining(String projectName, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return weiJianDispatchRecordRepository.findByProjectNameContaining(projectName, pageable);
    }
}